"""
Author : ZhengShiQi
dateTime: 2025/9/11 13:51
FileName: database.py
description: SQLAlchemy模型
"""

from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text, JSON
from sqlalchemy.ext.declarative import declarative_base
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.config import settings

# 1. 创建 MySQL 引擎
engine = create_engine(
    settings.DATABASE_URL,
    pool_pre_ping=True,  # 连接前检测，避免无效连接
    pool_recycle=3600  # 1小时回收连接，适配 MySQL 的 wait_timeout
)

# 2. 创建数据库会话（和 SQLite 逻辑一致，无需改）
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


# 数据库依赖项
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
Base = declarative_base()


# 模拟API配置表
class MockApiConfig(Base):
    __tablename__ = "mocks"

    id = Column(Integer, primary_key=True, index=True, comment="主键ID")
    wiremock_id = Column(String(36), nullable=True, comment="WireMock映射ID")
    name = Column(String(255), nullable=False, comment="Mock规则名称")
    url = Column(String(512), nullable=False, comment="被Mock的业务路径", index=True)
    method = Column(String(10), nullable=False, comment="HTTP方法")
    headers = Column(JSON, nullable=False, comment="返回头部（键值对）")
    body = Column(JSON, nullable=True, comment="返回体内容")
    status_code = Column(Integer, nullable=False, comment="HTTP状态码")
    status = Column(Boolean, default=True, nullable=False, comment="状态（1：开启，0：关闭）")
    created_at = Column(DateTime, default=datetime.utcnow, comment="创建时间")
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment="修改时间")